package main

import (
	"fmt"
	"strconv"
	"time"

	"github.com/xuri/excelize/v2"
)

func Merge(files []string) error {
	sum := make(map[string][]Rows)

	for _, file := range files {
		f, err := excelize.OpenFile(file)
		if err != nil {
			return fmt.Errorf("打开文件出错： %s", file)
		}
		defer func() {
			// Close the spreadsheet.
			if err := f.Close(); err != nil {
				return
			}
		}()
		sheets := f.GetSheetList()

		for _, sheet := range sheets {
			rows, err := f.GetRows(sheet)
			if err != nil {
				return fmt.Errorf("获取文件%s 的sheet： %s 出错: %s", file, sheet, err.Error())
			}
			if _, ok := sum[sheet]; !ok {
				sum[sheet] = make([]Rows, len(rows))
			}
			if len(rows) > len(sum[sheet]) {
				rs := make([]Rows, len(rows)-len(sum[sheet]))
				sum[sheet] = append(sum[sheet], rs...)
			}
			for index, row := range rows {
				err := sum[sheet][index].Add(row)
				if err != nil {
					return err
				}
			}
		}
	}

	return Write(sum)
}

func Write(data map[string][]Rows) error {
	f := excelize.NewFile()
	for key, sheet := range data {
		f.NewSheet(key)
		for rIndex, row := range sheet {
			for cINdex, cell := range row.Rows {
				icell, err := strconv.ParseFloat(cell, 64)
				if err != nil {
					f.SetCellValue(key, axis(rIndex, cINdex), cell)
				} else {
					f.SetCellFloat(key, axis(rIndex, cINdex), icell, 2, 64)
				}

			}
		}
	}
	now := time.Now()
	filename := fmt.Sprintf("合并结果-%d-%02d-%02d-%02d-%02d-%02d.xlsx",
		now.Year(), now.Month(), now.Day(), now.Hour(), now.Minute(), now.Second())
	err := f.SaveAs(filename)
	if err != nil {
		return err
	}
	return nil
}

func axis(r, c int) string {
	cows := []string{"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"}
	value := ""
	for {
		value += cows[c%len(cows)]
		c = c / len(cows)
		if c == 0 {
			break
		}
	}
	return fmt.Sprintf("%s%d", value, r+1)
}
